package com.yy.netwrok.response;

import android.os.Handler;
import android.os.Looper;

import com.yy.netwrok.exception.OkHttpException;
import com.yy.netwrok.listener.DisposeDataHandle;
import com.yy.netwrok.listener.DisposeDataListener;
import com.yy.netwrok.utils.ResponseEntityToModule;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CommonJsonCallback implements Callback {

    protected final String RESULT_CODE = "ecode";
    protected final int RESULT_CODE_VALUE = 0;
    protected final String ERROR_MSG = "emsg";
    protected final String EMPTY_MSG = "";

    protected final int NETWORK_ERROR = -1;
    protected final int JSON_ERROR = -2;
    protected final int OTHER_ERROR = -3;

    private DisposeDataListener mDisposeDataListener;
    private Class<?> mClass;
    private Handler mHandler;

    public CommonJsonCallback(DisposeDataHandle dataHandle) {
        mDisposeDataListener = dataHandle.mListener;
        mClass = dataHandle.mClass;
        mHandler = new Handler(Looper.myLooper());
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mDisposeDataListener.onFailure(new OkHttpException(NETWORK_ERROR, e));
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String result = response.body().string();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                handlerResponse(result);
            }
        });
    }

    private void handlerResponse(String result) {
        if (result == null || result.trim().length() == 0) {
            mDisposeDataListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
            return;
        }

        try {
            if (mClass == null) {
                mDisposeDataListener.onSuccess(result);
            } else {
                Object obj = ResponseEntityToModule.parseJsonToModule(result, mClass);
                if (obj != null) {
                    mDisposeDataListener.onSuccess(obj);
                } else {
                    mDisposeDataListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            mDisposeDataListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));

        }
    }
}
